package com.woniuxy.service;

import com.woniuxy.entity.Employee;
import com.woniuxy.entity.UserInfo;
import com.woniuxy.mapper.EmployeeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SecurityService implements UserDetailsService {
    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    EmployeeMapper employeeMapper;
    /**
     *
     * @param username 前端输入的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名到数据库中查询用户信息，主要包括账号密码 权限
        Employee employee = employeeMapper.queryEmployee(username);
        if(employee != null){
            employee.getPassword();//如果密码已经加密，直接放入
            String pw = passwordEncoder.encode(employee.getPassword());
            List<String> authCode = employee.getAuthCode();
            String authCodeStr = String.join(",", authCode);


//            return new User(employee.getAccount(),pw,
//                    AuthorityUtils.commaSeparatedStringToAuthorityList(authCodeStr));
            return new UserInfo(employee.getAccount(),pw,
                    AuthorityUtils.commaSeparatedStringToAuthorityList(authCodeStr),employee.getId());
        }else {
            throw new UsernameNotFoundException("用户名不存在");
        }

    }
}
